using System.Globalization;
using System.Windows;

namespace RRX.Xml.Helper
{
    public class PointSerializer
    {
        // Serialize an object to string using XML serialization

        public static string Serialize(List<Point> points)
        {
            string serialize = "";

            for (int i = 0; i < points.Count; i++)
            {

                if (i > 0)
                {
                    serialize = serialize + "|" + points[i].X.ToString(CultureInfo.InvariantCulture) + ";" + points[i].Y.ToString(CultureInfo.InvariantCulture);
                }
                else
                {
                    serialize = serialize + points[i].X.ToString(CultureInfo.InvariantCulture) + ";" + points[i].Y.ToString(CultureInfo.InvariantCulture);
                }
            }

            return serialize;
        }

        public static List<Point> Deserialize(string serializedPoints)
        {

            List<Point> deserialize = new List<Point>();

            string[] points = serializedPoints.Split('|');

            for (int i = 0; i < points.Length; i++)
            {
                Point p = new Point();

                p = ParsePoint(points[i]);

                deserialize.Add(p);
            }

            return deserialize;

        }

        private static Point ParsePoint(string pointString)
        {
            string[] pointParts = pointString.Split(';');
            return new Point(double.Parse(pointParts[0], CultureInfo.InvariantCulture), double.Parse(pointParts[1], CultureInfo.InvariantCulture));
        }


        public static string SerializeSingle(Point point)
        {
            string serialize = "";

            serialize = point.X.ToString(CultureInfo.InvariantCulture) + ";" + point.Y.ToString(CultureInfo.InvariantCulture);

            return serialize;
        }

        public static Point DeserializeSingle(string serializedPoint)
        {

            Point deserialize = new Point(0, 0);

            if (serializedPoint.Contains(";"))
            {
                string[] pointParts = serializedPoint.Split(';');
                deserialize = new Point(double.Parse(pointParts[0], CultureInfo.InvariantCulture), double.Parse(pointParts[1], CultureInfo.InvariantCulture));
            }


            return deserialize;

        }

        public static Point DeserializeMin(string serializedPoints)
        {
            string[] points = serializedPoints.Split('|');

            double minX = double.MaxValue;
            double minY = double.MaxValue;

            foreach (var pointStr in points)
            {
                Point p = ParsePoint(pointStr);

                if (p.X < minX)
                    minX = p.X;

                if (p.Y < minY)
                    minY = p.Y;
            }

            return new Point(minX, minY);
        }
    }
}
